<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="search-from">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <SearchResult v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <SearchSuggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <SearchHistory 
    :search-histories='searchHistories' 
    v-else
    @clear-search-histories='searchHistories=[]'
    @search='onSearch'
     />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
// 导入本地存储封装方法
import {setItem,getItem} from '@/utils/storage'
import SearchResult from "./components/search-result";
import SearchHistory from "./components/search-history";
import SearchSuggestion from "./components/search-suggestion";
export default {
  name: "SearchPage",
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  },
  props: {},
  data() {
    return {
      searchText: "",
      isResultShow: false, //控制搜索结果 显示状态
      searchHistories: getItem('clear-search-histories') || [] //存储历史数据
    };
  },
  computed: {},
  watch: {
    searchHistories(val){
      setItem('clear-search-histories',val)
    }
  },
  created() {},
  methods: {
    // 搜索框
    onSearch(val) {
      // 更新文本框内容
      this.searchText = val;
      // 存储搜索历史记录
      // 要求：不要有重复历史记录，最新的排在最前面
      const index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }
      this.searchHistories.unshift(val);
      // 渲染搜索结果
      this.isResultShow = true;
    },
    // 取消按钮
    onCancel() {
      this.$router.back();
    }
  }
};
</script>

<style scoped lang="less">
.search-container {
  // padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
}
</style>
